package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-hub/cache"
	"novel-hub/models"
	"novel-hub/pkj"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	var login models.User
	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误超过三次禁止登录",
		})
		return
	}
	err := models.DB.Debug().Where("username=?", username).Find(&login)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查找失败",
		})
		return
	}
	if login.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if login.Password != pkj.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,请两小时后重试",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": login,
		"msg":  "登录成功",
	})
	return
}
func List(c *gin.Context) {
	var list []models.User

	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Debug().Find(&list)
		jsonsDta, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonsDta, time.Hour*2)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonsDta, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": list,
		"msg":  "列表成功",
	})
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var list []models.User
	redis_key := "list_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Debug().First(&list)
		jsonsDta, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonsDta, time.Hour*2)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonsDta, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": list,
		"msg":  "详情成功",
	})
}
